import os
import sys
# DON'T CHANGE THIS !!!
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

from flask import Flask, send_from_directory
from flask_cors import CORS
from config import get_config
from src.models.database import db
from src.models.metaso_data import MetasoQueryData, MetasoWebpageData
from src.routes.data_management import data_bp
from src.routes.prediction import prediction_bp
from src.routes.reports import reports_bp
from src.routes.industry_data import industry_bp
from src.routes.metaso import metaso_bp
from src.routes.export import export_bp
from src.routes.llm import llm_bp

# 获取配置
config = get_config()

app = Flask(__name__, static_folder=os.path.join(os.path.dirname(__file__), 'static'))

# 应用配置
app.config.from_object(config)

# Enable CORS for all routes
CORS(app, origins=config.CORS_ORIGINS)

# Register blueprints
app.register_blueprint(data_bp, url_prefix='/api/v1/data')
app.register_blueprint(prediction_bp, url_prefix='/api/v1/prediction')
app.register_blueprint(reports_bp, url_prefix='/api/v1/reports')
app.register_blueprint(industry_bp, url_prefix='/api/v1/industry')
app.register_blueprint(metaso_bp, url_prefix='/api/v1/metaso')
app.register_blueprint(export_bp, url_prefix='/api/v1/export')
app.register_blueprint(llm_bp, url_prefix='/api/v1/llm')

# 初始化数据库
db.init_app(app)

with app.app_context():
    try:
        db.create_all()
        print("✅ 数据库表创建成功")
        print(f"📊 数据库连接: {config.SQLALCHEMY_DATABASE_URI}")
    except Exception as e:
        print(f"⚠️  数据库表创建警告: {str(e)}")
        print("如果表已存在，可以忽略此警告")
        print("请确保MySQL服务正在运行，并且数据库qilu_db已创建")

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve(path):
    static_folder_path = app.static_folder
    if static_folder_path is None:
        return "Static folder not configured", 404

    if path != "" and os.path.exists(os.path.join(static_folder_path, path)):
        return send_from_directory(static_folder_path, path)
    else:
        index_path = os.path.join(static_folder_path, 'index.html')
        if os.path.exists(index_path):
            return send_from_directory(static_folder_path, 'index.html')
        else:
            return "index.html not found", 404

@app.route('/api/health')
def health_check():
    return {'status': 'healthy', 'message': 'Prediction AI System is running'}

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

